package com.test.thread.virtualthread;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VirtualThreadScheduler {

    public static final ScopedValue<VirtualThread> CURRENT_VIRTUAL_THREAD = ScopedValue.newInstance();

    private final Queue<VirtualThread> queue = new ConcurrentLinkedQueue<>();

    private final ExecutorService executor = Executors.newFixedThreadPool(3);

    public void start() {
        while (true) {
            if (!queue.isEmpty()) {
                VirtualThread vt = queue.poll();
                executor.submit(() -> ScopedValue.where(CURRENT_VIRTUAL_THREAD, vt).run(vt::run));
            }
        }
    }

    public void schedule(VirtualThread virtualThread) {
        queue.add(virtualThread);
    }
}
